package cn.hua.trip.app.base.filter;

import cn.hua.trip.app.base.util.UploadUtil;
import org.apache.commons.io.FileUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

public class ImageFilter implements Filter{
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        //获得请求的uri
        String uri = req.getRequestURI();
        //这里做的是一个拼接路径
        File file = new File(UploadUtil.IMG_BASE_PATH, uri);
        //判断这个文件是否存在
        if (file.exists()) {
            //如果存在,先从公共的图片文件中读进来
            byte[] bytes = FileUtils.readFileToByteArray(file);
            //将读出来的数据通过浏览器写出去
            response.getOutputStream().write(bytes);
        }else{
            //如果这个文件不存在,则放行让服务器自己处理
            chain.doFilter(request,response);
        }
    }

    public void destroy() {

    }
}
